#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <fcntl.h>

#include "digmania.h"

/*
 * Set default values to program options.
 */
void set_default_client_options(client_options_t *opts)
{
	opts->window_width = 800;
	opts->window_height = 600;
	opts->color_depth = 32;
}

/*
 * Convert string to lower case.
 */
void lower_case(char *str)
{
	while (*str) {
		*str = tolower(*str);
		++str;
	}
}

/*
 * Read configuration file and return options structure.
 */
client_options_t *read_client_config(const char *path)
{
	client_options_t *opts = malloc(sizeof(client_options_t));
	if (!opts) {
		fprintf(stderr,"[fatal] memory allocation problem\n");
		exit(1);
	}
	
	set_default_client_options(opts);
	
	char file_buf[8192];
	char *buf = (char*) &file_buf;

	int fd = open(path, O_RDONLY, 0);
	if (fd == -1) {
		fprintf(stderr, "[warning] Can not open %s. Using default options.\n",
			path);
		return opts;
	}
	int c = read(fd, buf, 8191);
	buf[c] = 0;
	close(fd);
	
	char delims[] = " :=\t\r\n";
	char line_delims[] = "\r\n";
	char *token_end, *line, *line_end = buf;

	char *key, *value;
	while ((line = strtok_r(line_end, line_delims, &line_end))) {
		key = strtok_r(line, delims, &token_end);
		if (!key) continue;
		if (key[0] == '#') continue;

		value = strtok_r(token_end, delims, &token_end);
		if (!value) {
			fprintf(stderr, "[warning] %s: missing value for %s. Ignoring.\n",
				path, key);
			continue;
		}

		lower_case(key);
		if (!strcmp(key, "window_width")) opts->window_width = atoi(value);
		else if (!strcmp(key, "window_height")) opts->window_height = atoi(value);
		else if (!strcmp(key, "color_depth")) opts->color_depth = atoi(value);
		else {
			fprintf(stderr, "[warning] %s: unknown key \"%s\". Ignoring.\n",
				path, key);
		}
	}
	
	return opts;
}

/*
 * Free options structure.
 */
void destroy_client_options(client_options_t *opts)
{
	free(opts);
}
